package com.ruoyi.framework.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.webSocketConfig.WebSocket;
import com.ruoyi.common.utils.NameUtils;
import com.ruoyi.system.service.RadarLogService;
import com.ruoyi.system.service.impl.ApiService;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @Description:
 * @Author:let_free
 * @Date:2024/6/1/13:00
 **/
@Component
public class MyFileListener extends FileAlterationListenerAdaptor {
    @Autowired
    private ApiService apiService;

    @Autowired
    private RadarLogService radarLogService;


    @Autowired
    private WebSocket webSocket;


    private static final Logger logger = LoggerFactory.getLogger(MyFileListener.class);
    private boolean started = false;
    private boolean stopped = false;

    @Override
    public void onStart(FileAlterationObserver observer) {
        super.onStart(observer);
        if (!started) {
            logger.info("开始监听目录:" + observer.getDirectory());
            started = true;
        }
    }

    @Override
    public void onDirectoryCreate(File directory) {
        super.onDirectoryCreate(directory);
        logger.info("新建目录" + directory.getAbsolutePath());
    }

    @Override
    public void onDirectoryChange(File directory) {
        super.onDirectoryChange(directory);
        logger.info("修改目录" + directory.getAbsolutePath());
    }

    @Override
    public void onDirectoryDelete(File directory) {
        super.onDirectoryDelete(directory);
        logger.info("删除目录" + directory.getAbsolutePath());
    }

    //    监听新的雷达基文件
    @Override
    public void onFileCreate(File file) {
        super.onFileCreate(file);
        logger.info("新建文件" + file.getAbsolutePath());
//        传递路径给flask  实现解析雷达基数据并且保存
        HashMap<String, Object> map = new HashMap<>();
        map.put("path", file.getPath());
        String filename = NameUtils.getCurrentName(file.getName());
        map.put("filename", filename);
        //        插入基数据的历史记录
        CompletableFuture.supplyAsync(() -> {
            logger.info("插入雷达基数据到数据库" + file.getName());
            return radarLogService.insertRadarLog(file.getName());
        }).thenAccept(s -> {
//            //            八个小时之后的时间戳
//            String response = apiService.postAPI("/handleRadarBin", map);
//            handleRadarPrediction(response, filename,file.getPath());
            List<String> nameList = radarLogService.getLatestTenLog();
            HashMap<String, Object> map2 = new HashMap<>();
            map2.put("nameList", nameList);
            map2.put("currentName", filename);
            map2.put("type","wqeqe");
//            map.put("path",path);
//            接收flask返回的外推文件名
//            JSONObject response2 = JSONObject.parseObject(apiService.postAPI("/handlePredictionRadar", map));
//            map2.put("nameList", response2.get("data"));
            WebSocket.sendMessage(JSON.toJSONString(map2));
        });
    }

    public void handleRadarPrediction(String response, String filename,String path) {
        JSONObject result = JSONObject.parseObject(response);
        if (result.get("code").equals(200)) {
            logger.info("基数据解析和可视化保存成功,准备执行外推");
            List<String> nameList = radarLogService.getLatestTenLog();
            HashMap<String, Object> map = new HashMap<>();
            map.put("nameList", nameList);
            map.put("currentName", filename);
            map.put("path",path);

//            接收flask返回的外推文件名
            JSONObject response2 = JSONObject.parseObject(apiService.postAPI("/handlePredictionRadar", map));
            map.put("nameList", response2.get("data"));
            WebSocket.sendMessage(JSON.toJSONString(map));
        } else {
            throw new RuntimeException("基数据解析失败");
        }
    }

    @Override
    public void onFileChange(File file) {
        super.onFileChange(file);
        logger.info("修改文件" + file.getAbsolutePath());
    }

    @Override
    public void onFileDelete(File file) {
        super.onFileDelete(file);
        logger.info("删除文件" + file.getAbsolutePath());
    }

    @Override
    public void onStop(FileAlterationObserver observer) {
        super.onStop(observer);
    }
}
